import 'package:flutter_blue_plus/flutter_blue_plus.dart';

// 自定义蓝牙设备类
class CustomScanResult {
  final BluetoothDevice device;
  final AdvertisementData advertisementData;
  final int rssi;
  final DateTime timeStamp;
  String _sn = "";
  String _macAddress = "";

  CustomScanResult(
    this.device,
    this.advertisementData,
    this.rssi,
    this.timeStamp,
  ) {
    _sn = _getSn();
  }

  factory CustomScanResult.fromScanResult(ScanResult result) {
    return CustomScanResult(
      result.device,
      result.advertisementData,
      result.rssi,
      result.timeStamp,
    );
  }

  // 给sn添加setter方法
  set sn(String sn) {
    _sn = sn;
  }

  // 获取sn
  String get sn {
    if (_sn.isEmpty) {
      _sn = _getSn();
    }
    return _sn;
  }

  // 获取sn
  String _getSn() {
    // 蓝牙名称后6位
    String name = device.advName;
    if (name.length >= 6) {
      String lastSixChars = name.substring(name.length - 6);
      return lastSixChars.toUpperCase();
    }
    return "";
  }

  // 获取sn
  String get macAddress {
    return _getMac();
  }

  // 通过广播数据获取车辆mac
  String _getMac() {
    // 获取广播包数据
    List<int> manufacturerData =
        advertisementData.manufacturerData.values.firstOrNull ?? [];
    // 假设SN在制造商特定数据中，具体格式取决于设备厂商
    if (manufacturerData.isNotEmpty) {
      // 解析SN - 这里需要根据设备的具体协议来解析
      int snLen = 6;
      if (manufacturerData.length >= snLen) {
        List<int> snBytes = manufacturerData.sublist(0, snLen);
        _macAddress = snBytes
            .map((byte) => byte.toRadixString(16).padLeft(2, '0'))
            .join(':');
      }
    }
    return _macAddress;
  }
}
